import cloud from '@lafjs/cloud'
let dbName = "web-order"
const db = cloud.mongo.db

export default async function (ctx: FunctionContext) {
  let data = ctx.body

  let obj = {}
  if (data.year) {
    let arr = []

    //传入年份的start和end内
    const startOfYear = new Date(data.year, 0, 1).getTime(); // 该年份的开始时间戳
    const endOfYear = new Date(data.year, 11, 31, 23, 59, 59, 999).getTime(); // 该年份的结束时间戳

    //判断是否有挪至次年的标记，有的话是否等于传入的年份
    let aa = await db.collection(dbName).find({
      statisticsYear: {
        $exists: true,   // 判断属性存在[1,2](@ref)
        $eq: data.year        // 验证值等于2025[5](@ref)
      }
    }).project({ _id: 1 }).toArray()

    //没有标记，正常筛选
    let timeobj = {
      _add_time: { $gte: startOfYear, $lt: endOfYear },
      statisticsYear: { $exists: false }
    }
    let bb = await db.collection(dbName).find(timeobj).project({ _id: 1 }).toArray()

    let cc = [...aa, ...bb]
    cc.forEach(element => {
      arr.push(element._id)
    });

    obj["_id"] = { $in: arr } //特定的订单id
  }

  if (data.status && data.status.length) {
    let statusList = [...data.status]
    //如果有报名成功的状态，则添加到10状态
    if (statusList.includes(2) && !statusList.includes(10)) statusList.push(10)
    obj["status"] = { $in: statusList }
  }

  let fieldJson = { curriculum_id: 1, displayPrice: 1 }

  let curriculums = await db.collection("web-course").find({}).project({ _id: 1, name: 1 }).toArray()

  //console.log("入参", obj)
  let aa = await db.collection(dbName).find(obj).project(fieldJson).toArray()
  let result = cloud.utils.sameSortArr(aa, "curriculum_id")
  let maps = []

  function getTotal(array) {
    let num = 0
    array.forEach(element => {
      num += Number(element.displayPrice)
    });
    return num
  }

  result.forEach(element => {
    let index = cloud.utils.findIndexByField(curriculums, "_id", element.name)
    if (index != -1) {
      let query = {
        name: curriculums[index].name,
        curriculum_id: element.curriculum_id,
        curriculum_amount: element.origin.length,
        curriculum_total: getTotal(element.origin)
      }
      maps.push(query)
    }
  });

  return cloud.utils.requestReturn({ data: maps })
}
